<template>
  <div class="agent-config-container">
    <!-- 左侧列表 -->
    <div class="config-sidebar">
      <div class="sidebar-header">
        <h3>Agent 配置</h3>
        <el-button type="primary" size="small" @click="createNewConfig">
          <el-icon><Plus /></el-icon> 新建
        </el-button>
      </div>

      <div class="config-list" v-loading="loadingList">
        <div
          v-for="config in configs"
          :key="config.id"
          :class="['config-item', { active: currentConfig?.id === config.id }]"
          @click="selectConfig(config)"
        >
          <div class="config-item-header">
            <span class="config-name">{{ config.name }}</span>
            <el-tag v-if="config.is_active" type="success" size="small" effect="dark">使用中</el-tag>
          </div>
          <div class="config-desc">{{ config.description || '暂无描述' }}</div>
        </div>
      </div>
    </div>

    <!-- 右侧编辑区 -->
    <div class="config-main">
      <template v-if="currentConfig">
        <div class="main-header">
          <h2>{{ isEditing ? '编辑配置' : '新建配置' }}</h2>
          <div class="actions">
            <el-button
              v-if="currentConfig.id && !currentConfig.is_active"
              type="success"
              @click="activateConfig"
            >
              启用此配置
            </el-button>
            <el-button type="primary" @click="saveConfig">保存</el-button>
            <el-button
              v-if="currentConfig.id && !currentConfig.is_active"
              type="danger"
              @click="deleteConfig"
            >
              删除
            </el-button>
          </div>
        </div>

        <el-form :model="formData" label-position="top" class="config-form">
          <el-form-item label="配置名称" required>
            <el-input v-model="formData.name" placeholder="例如：开发助手" />
          </el-form-item>

          <el-form-item label="描述">
            <el-input v-model="formData.description" placeholder="简要描述该Agent的用途" />
          </el-form-item>

          <el-form-item label="系统提示词 (System Prompt)" required>
            <el-input
              v-model="formData.system_prompt"
              type="textarea"
              :rows="10"
              placeholder="你是一个智能助手..."
            />
            <div class="help-text">支持 Markdown 格式。系统会自动在开头注入当前时间信息。</div>
          </el-form-item>

          <el-form-item label="Agent 类型" required>
            <el-radio-group v-model="formData.agent_type">
              <el-radio label="langgraph">LangGraph Agent</el-radio>
              <el-radio label="deepagent">Deep Agent</el-radio>
            </el-radio-group>
            <div class="help-text">
              LangGraph: 支持自定义工具的传统 Agent<br>
              DeepAgent: 具有规划、文件系统和子 Agent 能力的深度 Agent
            </div>
          </el-form-item>

          <el-form-item label="模型选择" required>
            <el-select v-model="formData.model" placeholder="选择模型">
              <el-option
                v-for="model in availableModels"
                :key="model.id"
                :label="model.model + (model.remark ? ' - ' + model.remark : '')"
                :value="model.model"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="启用工具" v-if="formData.agent_type === 'langgraph'">
            <div class="tools-selection-area">
              <el-checkbox-group v-model="formData.tools">
                <div v-for="(tools, category) in groupedTools" :key="category" class="tool-category-group">
                  <div class="category-title">{{ category }}</div>
                  <div class="tool-grid">
                    <el-checkbox
                      v-for="tool in tools"
                      :key="tool.key"
                      :label="tool.key"
                      border
                      class="tool-checkbox-item"
                    >
                      <div class="tool-content">
                        <span class="tool-name">{{ tool.name }}</span>
                        <el-tooltip :content="tool.description" placement="top" :show-after="500">
                          <span class="tool-desc">{{ tool.description }}</span>
                        </el-tooltip>
                      </div>
                    </el-checkbox>
                  </div>
                </div>
              </el-checkbox-group>
              <div v-if="availableTools.length === 0" class="no-tools">
                暂无可用工具，请检查后端配置
              </div>
            </div>
          </el-form-item>
        </el-form>
      </template>
      <div v-else class="empty-state">
        <el-empty description="请选择或创建一个配置" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import agentApi from '@/services/agentConfig'
import modelApi from '@/services/modelConfig'

const loadingList = ref(false)
const configs = ref([])
const currentConfig = ref(null)
const availableTools = ref([])
const availableModels = ref([])
const isEditing = ref(false)

const formData = reactive({
  name: '',
  description: '',
  system_prompt: '',
  model: 'claude-3-5-sonnet-20241022',
  agent_type: 'langgraph',
  tools: []
})

// 按分类分组工具
const groupedTools = computed(() => {
  const groups = {}
  if (!availableTools.value) return groups
  
  availableTools.value.forEach(tool => {
    const category = tool.category || '其他工具'
    if (!groups[category]) {
      groups[category] = []
    }
    groups[category].push(tool)
  })
  return groups
})

// 加载数据
const loadData = async () => {
  loadingList.value = true
  try {
    const [configsRes, toolsRes, modelsRes] = await Promise.all([
      agentApi.getConfigs(),
      agentApi.getTools(),
      modelApi.getConfigs()
    ])
    configs.value = configsRes.data
    availableTools.value = toolsRes.data
    availableModels.value = modelsRes.data.filter(m => !m.is_disabled)

    // 如果有当前选中的配置，更新它
    if (currentConfig.value?.id) {
      const updated = configs.value.find(c => c.id === currentConfig.value.id)
      if (updated) {
        selectConfig(updated)
      }
    }
  } catch (error) {
    ElMessage.error('加载数据失败: ' + error.message)
  } finally {
    loadingList.value = false
  }
}

// 选择配置
const selectConfig = (config) => {
  currentConfig.value = config
  isEditing.value = true
  // 复制数据到表单
  Object.assign(formData, {
    name: config.name,
    description: config.description,
    system_prompt: config.system_prompt,
    model: config.model,
    agent_type: config.agent_type || 'langgraph',
    tools: config.tools || []
  })
}

// 新建配置
const createNewConfig = () => {
  currentConfig.value = { id: null } // 临时对象
  isEditing.value = false
  Object.assign(formData, {
    name: '',
    description: '',
    system_prompt: '',
    model: 'claude-3-5-sonnet-20241022',
    agent_type: 'langgraph',
    tools: []
  })
}

// 保存配置
const saveConfig = async () => {
  if (!formData.name || !formData.system_prompt) {
    ElMessage.warning('请填写名称和系统提示词')
    return
  }

  try {
    if (isEditing.value && currentConfig.value.id) {
      await agentApi.updateConfig(currentConfig.value.id, formData)
      ElMessage.success('更新成功')
    } else {
      const res = await agentApi.createConfig(formData)
      currentConfig.value = res.data // 更新为返回的新对象
      isEditing.value = true
      ElMessage.success('创建成功')
    }
    loadData()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 删除配置
const deleteConfig = () => {
  ElMessageBox.confirm('确定要删除这个配置吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await agentApi.deleteConfig(currentConfig.value.id)
      ElMessage.success('删除成功')
      currentConfig.value = null
      loadData()
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.response?.data?.detail || error.message))
    }
  })
}

// 激活配置
const activateConfig = async () => {
  try {
    await agentApi.activateConfig(currentConfig.value.id)
    ElMessage.success('已启用该配置')
    loadData()
  } catch (error) {
    ElMessage.error('启用失败: ' + error.message)
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.agent-config-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
}

.config-sidebar {
  width: 300px;
  background: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color);
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.config-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.config-item {
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 8px;
  transition: all 0.2s;
  border: 1px solid var(--el-border-color-lighter);
  background: var(--el-bg-color);
}

.config-item:hover {
  background: var(--el-fill-color-light);
  border-color: var(--el-border-color);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.config-item.active {
  background: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.config-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.config-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.config-desc {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.config-main {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: var(--el-bg-color);
  margin: 16px;
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color);
}

.main-header h2 {
  margin: 0;
  font-size: 20px;
  color: var(--el-text-color-primary);
}

.config-form {
  max-width: 800px;
}

.tools-selection-area {
  width: 100%;
  background: var(--el-fill-color-light);
  border-radius: 8px;
  padding: 16px;
}

.tool-category-group {
  margin-bottom: 16px;
}

.tool-category-group:last-child {
  margin-bottom: 0;
}

.category-title {
  font-weight: bold;
  color: var(--el-text-color-primary);
  margin-bottom: 12px;
  font-size: 14px;
  padding-left: 8px;
  border-left: 3px solid var(--el-color-primary);
}

.tool-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 12px;
}

.tool-checkbox-item {
  margin-right: 0 !important;
  width: 100%;
  height: auto !important;
  padding: 8px 12px !important;
}

.tool-checkbox-item :deep(.el-checkbox__label) {
  width: 100%;
  overflow: hidden;
}

.tool-content {
  display: flex;
  flex-direction: column;
  width: 100%;
  overflow: hidden;
}

.tool-name {
  font-weight: 500;
  margin-bottom: 2px;
}

.tool-desc {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.help-text {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.no-tools {
  color: var(--el-text-color-secondary);
  text-align: center;
  padding: 20px;
}
</style>
